package com.etalk.crm.serviceImpl;

import com.alibaba.fastjson.JSON;
import com.etalk.crm.dao.StudentReportCustomizeMapper;
import com.etalk.crm.dao.TextBooksMapper;
import com.etalk.crm.pojo.*;
import com.etalk.crm.service.StudentReportCustomizeService;
import com.etalk.crm.utils.DateUtil;
import io.swagger.models.auth.In;
import lombok.SneakyThrows;
import org.apache.commons.lang.StringEscapeUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.*;

/**
 * @author Jordan
 */
@Service
public class StudentReportCustomizeServiceImpl implements StudentReportCustomizeService {
    private static final Logger logger = LogManager.getLogger(StudentReportCustomizeServiceImpl.class);

    @Resource
    private StudentReportCustomizeMapper studentReportCustomizeMapper;
    @Resource
    private TextBooksMapper textBooksMapper;

    /**
     * 生成自定义学习报表
     * @param personId 学员id
     * @param startDate 开始时间
     * @param endDate 结束时间
     * @param creator 结束时间
     */
    @Transactional(rollbackFor=Exception.class)
    @Override
    public int createReportByCustomize(int personId, Date startDate, Date endDate, String creator) {
        logger.info("学员报表生成开始，开始时间[{}],结束时间[{}]",startDate,endDate);

        StudentReportCustomize studentReportCustomize = studentReportCustomizeMapper.selectPersonAndClassHourInfoByCustomize(personId,startDate, endDate);
        if (studentReportCustomize != null && studentReportCustomize.getPersonId()>0) {
            StudentReportCustomize mistakeStudentReportCustomize = studentReportCustomizeMapper.selectWrongQuestionInfoByCustomize(personId,startDate, endDate);
            StudentReportCustomize orderStudentReportCustomize = studentReportCustomizeMapper.selectOrderRemainHoursByCustomize(personId,startDate, endDate);
            StudentReportCustomize teacherStudentReportCustomize = studentReportCustomizeMapper.selectCommonTeacherInfoByCustomize(personId,startDate, endDate);
            //组合数据

            studentReportCustomize.setStartTime(startDate);
            studentReportCustomize.setEndTime(endDate);
            studentReportCustomize.setGrammarMistake(0);
            studentReportCustomize.setPronunciationMistake(0);
            studentReportCustomize.setWordMistake(0);
            studentReportCustomize.setRemainHours(BigDecimal.ZERO);
            studentReportCustomize.setTeacherImage("");
            studentReportCustomize.setTeacherLogin("");
            studentReportCustomize.setCreator(creator);
            if (org.apache.commons.lang3.StringUtils.isEmpty(studentReportCustomize.getNamedContentIds())){
                studentReportCustomize.setNamedContentIds("");
                studentReportCustomize.setNamedTimes(0);
            }else {
                studentReportCustomize.setNamedTimes(studentReportCustomize.getNamedContentIds().split(",").length);
            }
            if (org.apache.commons.lang3.StringUtils.isEmpty(studentReportCustomize.getEvaluateLessonIds())){
                studentReportCustomize.setEvaluateLessonIds("");
            }
            //根据时间段计算建议上的课时，建议一周5节课
            int days= DateUtil.daysBetween(startDate,endDate);
            studentReportCustomize.setRecommendHoursThis(Math.round(days*5/7));
            if (StringUtils.isEmpty(studentReportCustomize.getSscLogin())) {
                studentReportCustomize.setSscLogin("");
            }
            if (StringUtils.isEmpty(studentReportCustomize.getTotalClass())) {
                studentReportCustomize.setTotalClass(0);
            }
            if (StringUtils.isEmpty(studentReportCustomize.getKnowledgeNum())) {
                studentReportCustomize.setKnowledgeNum(0);
            }
            if (StringUtils.isEmpty(studentReportCustomize.getKnowledgeError())) {
                studentReportCustomize.setKnowledgeError(0);
            }
            if (StringUtils.isEmpty(studentReportCustomize.getTotalComplete())){
                studentReportCustomize.setTotalComplete(0);
            }
            if (StringUtils.isEmpty(studentReportCustomize.getAttendanceRate())){
                studentReportCustomize.setAttendanceRate(0);
            }
            if (StringUtils.isEmpty(studentReportCustomize.getNamedTimes())){
                studentReportCustomize.setNamedTimes(0);
            }
            if (StringUtils.isEmpty(studentReportCustomize.getFourStarFeedback())){
                studentReportCustomize.setFourStarFeedback(0);
            }
            //计算打败百分之多少人
            studentReportCustomize.setDefeatedPeopleNum(BigDecimal.ZERO);
            if (StringUtils.isEmpty(studentReportCustomize.getStuCnName())) {
                studentReportCustomize.setStuCnName("");
            }

            if (mistakeStudentReportCustomize != null) {
                studentReportCustomize.setGrammarMistake(mistakeStudentReportCustomize.getGrammarMistake());
                studentReportCustomize.setPronunciationMistake(mistakeStudentReportCustomize.getPronunciationMistake());
                studentReportCustomize.setWordMistake(mistakeStudentReportCustomize.getWordMistake());
            }
            if (orderStudentReportCustomize != null) {
                studentReportCustomize.setRemainHours(orderStudentReportCustomize.getRemainHours().divide(BigDecimal.valueOf(100),2,BigDecimal.ROUND_HALF_UP));
            }
            if (teacherStudentReportCustomize != null) {
                studentReportCustomize.setTeacherImage(teacherStudentReportCustomize.getTeacherImage());
                studentReportCustomize.setTeacherLogin(teacherStudentReportCustomize.getTeacherLogin());
            }
            try {
                // 插入数据
                int num = studentReportCustomizeMapper.insertBatchReportList(studentReportCustomize);
                if (num > 0) {
                    logger.info("学员报表数据库月报信息，插入记录数：[{}]" ,num);

                }
                logger.info("学员报表生成结束，开始时间[{}],结束时间[{}]",startDate,endDate);
                return num;
            }catch (DuplicateKeyException e){
                logger.error(e);
                return -1;
            }
        }
        return 0;
    }

    /**
     * 生成阶段测试反馈
     * @param personId 学员id
     * @param startDate 开始时间
     * @param endDate 结束时间
     * @param creator 结束时间
     */
    @Transactional(rollbackFor=Exception.class)
    @Override
    public int createFeedback(int personId, Date startDate, Date endDate, String creator, StudentReportCustomizeDetail record){
        int num=0;
        if (record!=null) {
            record.setStartTime(startDate);
            record.setEndTime(endDate);
            record.setCreator(creator);
            boolean isAdd=false;
            if (!StringUtils.isEmpty(record.getMasteredKnowledge())){
                record.setMasteredKnowledge(StringEscapeUtils.escapeSql(record.getMasteredKnowledge()));
                isAdd=true;
            }
            if (!StringUtils.isEmpty(record.getNotMasteredKnowledge())){
                record.setNotMasteredKnowledge(StringEscapeUtils.escapeSql(record.getNotMasteredKnowledge()));
                isAdd=true;
            }
            if (!StringUtils.isEmpty(record.getStudySuggestions())){
                record.setStudySuggestions(StringEscapeUtils.escapeSql(record.getStudySuggestions()));
                isAdd=true;
            }
            if (!StringUtils.isEmpty(record.getProgressTerm())){
                record.setProgressTerm(StringEscapeUtils.escapeSql(record.getProgressTerm()));
                isAdd=true;
            }
            if (!StringUtils.isEmpty(record.getStudyContents())){
                record.setStudyContents(StringEscapeUtils.escapeSql(record.getStudyContents()));
                isAdd=true;
            }
            if (!StringUtils.isEmpty(record.getStudyFrequency())){
                record.setStudyFrequency(StringEscapeUtils.escapeSql(record.getStudyFrequency()));
                isAdd=true;
            }
            if (!StringUtils.isEmpty(record.getChangeMaterial())){
                record.setChangeMaterial(StringEscapeUtils.escapeSql(record.getChangeMaterial().trim()));
                isAdd=true;
            }
            if (!StringUtils.isEmpty(record.getStudyFocus())){
                record.setStudyFocus(StringEscapeUtils.escapeSql(record.getStudyFocus().trim()));
                isAdd=true;
            }
            if (!StringUtils.isEmpty(record.getTeaComplaint())){
                record.setTeaComplaint(StringEscapeUtils.escapeSql(record.getTeaComplaint().trim()));
                isAdd=true;
            }
            if (!StringUtils.isEmpty(record.getTestResults())){
                record.setTestResults(StringEscapeUtils.escapeSql(record.getTestResults().trim()));
                isAdd=true;
            }
            if (!StringUtils.isEmpty(record.getHomework())){
                record.setHomework(StringEscapeUtils.escapeSql(record.getHomework().trim()));
                isAdd=true;
            }
            if (isAdd) {
                num = studentReportCustomizeMapper.insertDetail(record);
                if (record.getParamList()!=null && record.getParamList().size()>0){
                    for (ReportSubmitParam param:record.getParamList()){
                        if(!StringUtils.isEmpty(param.getTypeContent())) {
                            param.setTypeContent(param.getTypeContent().replaceFirst("/", "").replace(",/", " | "));
                        }
                    }
                    studentReportCustomizeMapper.insertCustomizeDetailKnowledge(record.getId(),record.getParamList());
                }
                logger.info("学员报表生成添加阶段检查反馈信息成功");
            }
        }
        return num;
    }

    /**
     * 获取错词和知识点数据，掌握与未掌握分开
     * @param personId 学员id
     * @return
     */
    @SneakyThrows
    @Override
    public Map<String,Object> searchMistakeKnowledgeByPersonId(Integer personId){
        Map<String,Object> resultMap=new HashMap<>(4);

        List<Map<String,Object>> listClassMap=studentReportCustomizeMapper.selectLtClassTimeByPersonId(personId);
        if (listClassMap==null || listClassMap.size()==0 || listClassMap.get(0).get("release_time").equals(listClassMap.get(0).get("startTime"))){
            return resultMap;
        }
        Date startTime = DateUtils.parseDate(listClassMap.get(0).get("startTime").toString(),"yyyy-MM-dd HH:mm:ss.SSS");
        Date endTime=DateUtils.parseDate(listClassMap.get(0).get("release_time").toString(),"yyyy-MM-dd HH:mm:ss.SSS");
        if (listClassMap.size()>1){
            startTime = DateUtils.parseDate(listClassMap.get(1).get("release_time").toString(),"yyyy-MM-dd HH:mm:ss.SSS");
        }

        /*Date startTime = DateUtils.parseDate("2020-03-01 00:00:00","yyyy-MM-dd HH:mm:ss");
        Date endTime=DateUtils.parseDate("2020-05-01 00:00:00","yyyy-MM-dd HH:mm:ss");*/
        resultMap.put("startTime",startTime);
        resultMap.put("endTime",endTime);
        //查询课程总体情况
        StudentReportCustomizeDetail scd = studentReportCustomizeMapper.selectClassPerformanceByPersonId(personId,startTime,endTime);
        //查询旷课和被投诉次数
        StudentReportCustomizeDetail tempScd=studentReportCustomizeMapper.selectLateComplaintNumByPersonId(personId,startTime,endTime);
        scd.setNamedNum(tempScd.getNamedNum());
        scd.setNoShowNum(tempScd.getNoShowNum());
        resultMap.put("classInfo",scd);

        //最后一节中教课的课程id
        int ltLessonId=Integer.parseInt(listClassMap.get(0).get("id").toString());
        //查询中教错词本
        List<MistakeKnowledge> listMistake=studentReportCustomizeMapper.selectLtMistakeBookListByLessonId(ltLessonId);
        StringBuffer mistakeErr=new StringBuffer("具体表现为：\n");
        String newLineStr="语法";
        if (listMistake!=null && listMistake.size()>0) {
            int listMistakeSize = listMistake.size();
            if (listMistakeSize >= 1 && listMistake.get(0)!=null) {
                if (newLineStr.equals(listMistake.get(0).getFirstName())){
                    mistakeErr.append("①未掌握的").append(listMistake.get(0).getFirstName()).append("：").append(listMistake.get(0).getErrInfo().replace(" | ","\n")).append("\n");
                }else {
                    mistakeErr.append("①未掌握的").append(listMistake.get(0).getFirstName()).append("：").append(listMistake.get(0).getErrInfo()).append("\n");
                }
            }
            if (listMistakeSize >= 2 && listMistake.get(1)!=null) {
                if (newLineStr.equals(listMistake.get(1).getFirstName())){
                    mistakeErr.append("②未掌握的").append(listMistake.get(1).getFirstName()).append("：").append(listMistake.get(1).getErrInfo().replace(" | ","\n")).append("\n");
                }else {
                    mistakeErr.append("②未掌握的").append(listMistake.get(1).getFirstName()).append("：").append(listMistake.get(1).getErrInfo()).append("\n");
                }
            }
            if (listMistakeSize >= 3 && listMistake.get(2)!=null) {
                if (newLineStr.equals(listMistake.get(2).getFirstName())){
                    mistakeErr.append("③未掌握的").append(listMistake.get(2).getFirstName()).append("：").append(listMistake.get(2).getErrInfo().replace(" | ","\n")).append("\n");
                }else {
                    mistakeErr.append("③未掌握的").append(listMistake.get(2).getFirstName()).append("：").append(listMistake.get(2).getErrInfo()).append("\n");
                }
            }
        }
        resultMap.put("mistakeErr",mistakeErr);
        //用于知识点选择框
        resultMap.put("mistakeSelect",JSON.toJSONString(listMistake));
        resultMap.put("knowledgeMaterial",textBooksMapper.selectTextbooksByKnowledge());

        //查询两节中教课之间的外教课程id
        List<Integer> listLessonId=studentReportCustomizeMapper.selectLtLessonIdByPersonId(personId,DateUtils.addMinutes(startTime,1),endTime);
        //查询中教课已掌握的错词或知识点
        List<MistakeKnowledge> listMistakeKnowledge=studentReportCustomizeMapper.selectMistakeKnowledgeListByLessonId(listLessonId);

        StringBuffer mistakeRight=new StringBuffer("具体表现为：\n");
        //String newLineStr="语法";
        if (listMistakeKnowledge!=null && listMistakeKnowledge.size()>0){
            int listMistakeSize=listMistakeKnowledge.size();
            if (listMistakeSize>=1 && listMistakeKnowledge.get(0)!=null){
                if (newLineStr.equals(listMistakeKnowledge.get(0).getFirstName())){
                    mistakeRight.append("①已掌握的目标").append(listMistakeKnowledge.get(0).getFirstName()).append("：").append(listMistakeKnowledge.get(0).getErrInfo().replace(" | ","\n")).append("\n");
                }else {
                    mistakeRight.append("①已掌握的目标").append(listMistakeKnowledge.get(0).getFirstName()).append("：").append(listMistakeKnowledge.get(0).getErrInfo()).append("\n");
                }
            }
            if (listMistakeSize>=2 && listMistakeKnowledge.get(1)!=null){
                //mistakeRight.append( "②已掌握的目标").append(listMistakeKnowledge.get(1).getFirstName()).append("：").append(listMistakeKnowledge.get(1).getErrInfo()).append("\n");
                if (newLineStr.equals(listMistakeKnowledge.get(1).getFirstName())){
                    mistakeRight.append("②已掌握的目标").append(listMistakeKnowledge.get(1).getFirstName()).append("：").append(listMistakeKnowledge.get(1).getErrInfo().replace(" | ","\n")).append("\n");
                }else {
                    mistakeRight.append("②已掌握的目标").append(listMistakeKnowledge.get(1).getFirstName()).append("：").append(listMistakeKnowledge.get(1).getErrInfo()).append("\n");
                }
            }
            if (listMistakeSize>=3 && listMistakeKnowledge.get(2)!=null){
                if (newLineStr.equals(listMistakeKnowledge.get(2).getFirstName())){
                    mistakeRight.append("③已掌握的目标").append(listMistakeKnowledge.get(2).getFirstName()).append("：").append(listMistakeKnowledge.get(2).getErrInfo().replace(" | ","\n")).append("\n");
                }else {
                    mistakeRight.append("③已掌握的目标").append(listMistakeKnowledge.get(2).getFirstName()).append("：").append(listMistakeKnowledge.get(2).getErrInfo()).append("\n");
                }
            }
        }
        resultMap.put("mistakeRight",mistakeRight);

        /*StringBuffer materialStr=new StringBuffer("Material 教材名称：");
        materialStr.append("02.1-2-2").append("\n");
        materialStr.append("Page is changed to 页码调整至：Unit: 2 ; Page: 24").append("\n");
        materialStr.append("Date调整日期：").append(LocalDate.now()).append("\n");
        resultMap.put("changeMaterial",materialStr);*/

        //查询老师投诉学员标签
        List<String> listComplaint=studentReportCustomizeMapper.selectTeacherComplaintByPersonId(personId,startTime, endTime);
        resultMap.put("listComplaint",listComplaint);

        //查询未掌握知识点第一级分类列表
        List<KnowledgePointClassification> listClassification=studentReportCustomizeMapper.selectKnowledgePointClassificationListByParentId(0);
        resultMap.put("listType",listClassification);

        String studySuggestions=studentReportCustomizeMapper.selectLtStudySuggestions(ltLessonId);
        resultMap.put("studySuggestions",studySuggestions);
        //查询学习建议第一级分类
        List<Map<String,Object>> listGrade=studentReportCustomizeMapper.selectStudySuggestionsGrade();
        resultMap.put("listGrade",listGrade);

        List<Map<String,Object>> listKnowledge=studentReportCustomizeMapper.selectStudySuggestionsKnowledgeByGradeId();
        resultMap.put("listKnowledge",listKnowledge);

        //查询测试情况
        List<StudentReportCustomize> listTestScores=studentReportCustomizeMapper.selectTestScoresByPersonId(personId,startTime, endTime);
        if (listTestScores!=null && listTestScores.size() > 0) {
            List<String> listTemp=new ArrayList<>(listTestScores.size());
            for (StudentReportCustomize record:listTestScores){
                switch (record.getState()){
                    case 0:
                        listTemp.add("《"+record.getTestName()+"》(未做)");
                        break;
                    case 1:
                        listTemp.add("《"+record.getTestName()+"》(待批改)");
                        break;
                    case 2:
                        listTemp.add("《"+record.getTestName()+"》得分：" + record.getScore()+"分(待讲解)");
                        break;
                    case 3:
                        listTemp.add("《"+record.getTestName()+"》得分：" + record.getScore()+"分(已讲解)");
                        break;
                    default :
                }
            }
            resultMap.put("listTestScores", listTemp);
        }

        StudentReportCustomize practiceQuestion=studentReportCustomizeMapper.selectPracticeQuestionByPersonId(personId,startTime, endTime);
        if (practiceQuestion!=null){
            resultMap.put("homeworkRate",practiceQuestion.getFinishNum().divide(practiceQuestion.getTotal(),2,BigDecimal.ROUND_HALF_UP).multiply(BigDecimal.valueOf(100)).stripTrailingZeros());
        }
//        logger.info(JSON.toJSONString(resultMap));
        return resultMap;
    }
    /**
     * 知识点设置json格式
     * @param list 查询结果
     * @return json格式
     */
    private List<Map<String,Object>> setMistakeKnowledgeList(List<MistakeKnowledge> list){
        List<Map<String,Object>> result=new ArrayList<>();
        if (list!=null && list.size()>0){
            Map<String,Object> firstMap;
            List<Map<String,Object>> firstChildList = null;
            Map<String,Object> secondMap;
            List<Map<String,Object>> secondChildList = null;
            Map<String,Object> thirdMap;
            List<String> thirdChildList = null;

            List<String> listErr=new ArrayList<>();
            String firstNameTemp="";
            String secondNameTemp="";
            String thirdNameTemp="";
            for (MistakeKnowledge record:list){
                if (!firstNameTemp.equals(record.getFirstName())){
                    firstNameTemp=record.getFirstName();
                    firstMap=new HashMap<>();
                    firstMap.put("name",record.getFirstName());
                    firstChildList=new ArrayList<>();
                    firstMap.put("child",firstChildList);
                    result.add(firstMap);
                }

                if (!secondNameTemp.equals(record.getSecondName())){
                    secondNameTemp=record.getSecondName();
                    secondMap=new HashMap<>();
                    secondMap.put("name",record.getSecondName());
                    secondChildList=new ArrayList<>();
                    secondMap.put("child",secondChildList);
                    firstChildList.add(secondMap);
                }

                if (!thirdNameTemp.equals(record.getThirdName())){
                    thirdNameTemp=record.getThirdName();
                    thirdMap=new HashMap<>();
                    thirdMap.put("name",record.getThirdName());
                    thirdChildList=new ArrayList<>();
                    thirdMap.put("child",thirdChildList);
                    secondChildList.add(thirdMap);
                }
                thirdChildList.add(record.getErrInfo());

            }
        }
        return result;
    }

    /**
     * 查询英语知识点列表选项
     * @param parentId 父级id
     * @return
     */
    @Override
    public List<KnowledgePointClassification> searchKnowledgePointClassificationListByParentId(int parentId){
        List<KnowledgePointClassification> list = studentReportCustomizeMapper.selectKnowledgePointClassificationListByParentId(parentId);
        for (KnowledgePointClassification record:list){
            if (record.getId()==42 || record.getId()==49){
                record.setListChild(studentReportCustomizeMapper.selectKnowledgePointClassificationListByParentId(record.getId()));
            }
        }
        return list;
    }

    /**
     * 查询教材对应的知识点
     * @param textbookId 教材id
     * @return
     */
    @Override
    public List<String> searchKnowledgeListByTextbookId(int textbookId){
        return textBooksMapper.selectKnowledgeByTextbookId(textbookId);
    }

    /**
     * 根据年级查询学习建议的知识点分类
     * @param knowledgeId 学习建议知识点分类id
     * @return
     */
    @Override
    public List<Map<String,Object>> searchStudySuggestionsKnowledgeByKnowledgeId(int gradeId,List<Integer> knowledgeId){
        List<Map<String,Object>> resultList=new ArrayList<>();
        List<Map<String,Object>> list = studentReportCustomizeMapper.selectStudySuggestionsContentByKnowledgeId(gradeId,knowledgeId);
        if (list!=null && list.size()>0){
            Map<String,Object> resultMap;
            List<Map<String,Object>> childList=null;
            int tempKnowledgeId=0;
            for (Map<String,Object> record:list){
                if (Integer.parseInt(record.get("knowledge_id").toString())!=tempKnowledgeId){
                    tempKnowledgeId=Integer.parseInt(record.get("knowledge_id").toString());
                    resultMap=new HashMap<>(2);
                    resultMap.put("name",record.get("knowledgeName"));
                    childList=new ArrayList<>();
                    resultMap.put("list",childList);
                    resultList.add(resultMap);
                }
                record.remove("knowledge_id");
                record.remove("knowledgeName");
                childList.add(record);
            }
        }
        return resultList;
    }

    /**
     * 查询阶段检测反馈信息
     * @param id 反馈id
     * @return 信息
     */
    @Override
    public StudentReportCustomizeDetail searchFeedbackInfoById(int id){
        return studentReportCustomizeMapper.selectStageFeedbackInfoById(id);
    }
}
